import { routers } from './routers.js'
import { createRouter,createWebHashHistory,createWebHistory  } from "vue-router";
import { useUserInfoStore } from '../store/index.js';

const router = createRouter({
    history: createWebHashHistory(),
    routes: routers,
    // 每次切换路由后滚动条置顶
    scrollBehavior(to, from, savedPosition) {
        return { left: 0, top: 0 }
    }
})


router.beforeEach((to, from, next) => {
    const userStore = useUserInfoStore();
    const isAuthenticated = !!userStore.userInfo;
    if (to.meta.requiresAuth && !isAuthenticated) {// 如果路由需要认证，但用户未登录，则重定向到登录页面
        next({ name: 'login' });
    } else {// 否则，允许路由继续
        next();
    }
});

export default router